package com.vito.framework.system.org.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vito.framework.base.controller.BaseController;
import com.vito.framework.base.exception.CommonException;
import com.vito.framework.rest.bean.AppSession;
import com.vito.framework.system.menu.model.MenuBean;
import com.vito.framework.system.menu.service.MenuService;
import com.vito.framework.system.menu.service.impl.MenuTree;
import com.vito.framework.system.org.model.OrgBean;
import com.vito.framework.system.org.service.OrgManageService;
import com.vito.support.ApiResponse;
import com.vito.support.ResultEnum;
import com.vito.util.excel.ExportBean;
import com.vito.util.excel.ExportExcelJxl;
import com.vito.util.excel.ImportExcelUtil;
import com.vito.util.excel.ImportExcelUtilImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***************************************************************
 * Name: OrgManageController.java Create At: 2017年9月5日 Module: Description:
 * [功能描述]机构管理
 * 
 * @author ztshan ------------------------------------------------------------
 *         修改历史 序号 日期 修改人 修改原因 1 2017年9月5日 ztshan 2
 ***************************************************************/
@RestController
@RequestMapping("${adminPath}/org")
public class OrgController extends BaseController {

    @Autowired
    private OrgManageService orgManageService;
    @Autowired
    private MenuService menuService;
    

    /**
     * Author:zhaoyue Create At:2012-10-25 Description: [机构管理-添加功能，查询机构编号是否已存在]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "checkOrgId", consumes = "application/json;charset=UTF-8")
    public ApiResponse checkOrgId(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    paramMap.put("param_orgId", params.getString("param_orgId"));

	    // 获取数据
		String count = orgManageService.queryTemplateList(paramMap);
        return ApiResponse.ok(count);
    }

    /**
     * Author:cail Create At:2010-06-12 Description: [系统运维-机构管理功能，批量删除机构信息]
     * 
     * @return String
     */
    @PostMapping(value = "delete", consumes = "application/json;charset=UTF-8")
    public ApiResponse delete(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
        	String orgId = (String) paramMap.get("cur_orgId");
        	String userId = (String) paramMap.get("cur_userId");
	        paramMap.put("orgId", orgId);
	        paramMap.put("userId", userId);

	        String org_id=params.getString("delOrgId");
			String[] ids=org_id.split(",");
	        paramMap.put("ids", ids);
            // 删除机构信息
            orgManageService.deleteOrgManage(paramMap);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:cail Create At:2010-06-12 Description: [系统运维-机构管理功能，修改机构-查询出机构的资料]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "get", consumes = "application/json;charset=UTF-8")
    public ApiResponse get(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    try {
            String orgId = params.getString("orgId");
            String userId=params.getString("userId");
		    paramMap.put("userId", userId);
		    paramMap.put("orgId", orgId);

            // 根据机构编号查询该机构信息
            OrgBean orgBean = orgManageService.getOrgManageById(paramMap);
		    return ApiResponse.ok(orgBean);
	    } catch (CommonException e) {
		    return ApiResponse.of(e);
	    }
    }

    /**
     * Author:cail Create At:2010-06-12 Description: [系统运维-机构管理功能，保存修改]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "edit", consumes = "application/json;charset=UTF-8")
    public ApiResponse edit(HttpServletRequest request, @RequestBody JSONObject params,OrgBean orgBean) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
        	orgBean= JSONObject.toJavaObject(params, OrgBean.class);
            orgManageService.updateOrgManage(orgBean);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:cail Create At:2010-06-12 Description: [系统运维-机构管理功能，保存新添加的机构]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "add", consumes = "application/json;charset=UTF-8")
    public ApiResponse add(HttpServletRequest request, @RequestBody JSONObject params,OrgBean orgBean) throws Exception {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
        	orgBean= JSONObject.toJavaObject(params, OrgBean.class);
            orgManageService.insertOrgManage(orgBean);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:cail Create At:2010-06-12 Description: [系统运维-机构管理功能，查询机构列表]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "list", consumes = "application/json;charset=UTF-8")
    public ApiResponse list(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

//	    paramMap.put("param_orgName", params.getString("param_orgName"));
//	    paramMap.put("param_orgAddr", params.getString("param_orgAddr"));
//	    paramMap.put("param_manager", params.getString("param_manager"));
	    paramMap.put("param_keyword", params.getString("param_keyword"));
	    try {
		    String orgId =(String) paramMap.get("cur_orgId");
		    paramMap.put("param_orgId", orgId);
            //非一级机构只能查看自己所在的机构
            String orgLevel = orgManageService.getOrgLevel(orgId);
            if(!StrUtil.isEmpty(orgLevel)) {
                if (Integer.parseInt(orgLevel) == 1) {
    	            paramMap.remove("param_orgId");
                }

            }
            // 查询机构列表
		    List<OrgBean> resultList = orgManageService.getOrgManageList(paramMap);
		    return ApiResponse.ok(resultList);
	    } catch (CommonException e) {
		    return ApiResponse.of(e);
	    }
    }

    /**
     * Author:xiaoqi Create At:2017-08-24 Description: [系统运维-机构管理功能，导入查询机构列表]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "importOrgManager")
    public ApiResponse importOrgManager(HttpServletRequest request, @RequestBody JSONObject params, @RequestParam MultipartFile file) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
            InputStream fis = file.getInputStream();
            ImportExcelUtil importExcelUtil = new ImportExcelUtilImpl();
            List<String[]> list = importExcelUtil.readXLSDocument(fis, 1, 5);
            List<OrgBean> beanList = new ArrayList<OrgBean>();
            for (String[] data : list) {
                OrgBean orgBean = new OrgBean();
                orgBean.setOrgId(data[0].trim());
                orgBean.setOrgName(data[1].trim());
                orgBean.setOrgAddr(data[2].trim());
                orgBean.setPhone(data[3].trim());
                orgBean.setZipcode(data[4].trim());
                orgBean.setOrgType("0");
                orgBean.setStatus("1");
                String porgId = data[0];
                if (data[0].length() != 2) {
                    porgId = data[0].trim().substring(0, data[0].trim().length() - 2);
                }
                orgBean.setPorgId(porgId);
                String level = Integer.toString(data[0].trim().length() / 2);
                orgBean.setLevel(level);
                beanList.add(orgBean);
            }
            orgManageService.insertOrgManageList(beanList);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (Exception e) {
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:xiaoqi Create At:2017-08-24 Description: [系统运维-机构管理功能，导出查询机构列表]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "exportOrgManager")
    public ApiResponse exportOrgManager(HttpServletRequest request, @RequestBody JSONObject params, HttpServletResponse response) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
		AppSession session = super.getUserSession(request);

	    paramMap.put("param_orgName", params.getString("param_orgName"));
	    paramMap.put("param_orgAddr", params.getString("param_orgAddr"));
	    paramMap.put("param_manager", params.getString("param_manager"));

    	try {
            String orgId = session.getMerchantId();
            String userId = session.getUserId();
		    paramMap.put("orgId", orgId);
		    paramMap.put("userId", userId);

            // 查询机构列表
            List<OrgBean> resultList = orgManageService.getOrgManageList(paramMap);
            int len = resultList.size();
            Object[][] data = new Object[len + 1][5];
            data[0] = new Object[] { "机构代码", "机构名称", "机构地址", "机构电话", "机构邮编" };
            int i = 1;
            for (OrgBean orgBean : resultList) {
                data[i][0] = orgBean.getOrgId();
                data[i][1] = orgBean.getOrgName();
                data[i][2] = orgBean.getOrgAddr();
                data[i][3] = orgBean.getPhone();
                data[i][4] = orgBean.getZipcode();
                i++;
            }
            ExportBean excelBean = new ExportBean();
            excelBean.setData(data);
            excelBean.setExcelName("组织机构");
            excelBean.setSheetName("组织机构");
            excelBean.setExportMode(0);
            new ExportExcelJxl(response, excelBean);
		    return ApiResponse.ok(ResultEnum.OK);
	    } catch (Exception e) {
		    return ApiResponse.of(e);
	    }
    }

    /**
     * Author:zhangyanling Create At:2012-06-04 Description: [系统管理-查询菜单树]
     * 
     * @return String
     */
    @PostMapping(value = "getMeanListTree", consumes = "application/json;charset=UTF-8")
    public ApiResponse getMeanListTree(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
	    try {
	    	List<MenuBean> list = menuService.getMenuList(paramMap);
	    	list = MenuTree.buildDivMenuTreeData(list);
		    return ApiResponse.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.of(e);
        }

    }
    
    /**
     * Author:zhangyanling Create At:2012-07-13 Description:
     * [系统管理-查询菜单树中默认选中菜单ID]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "getMenus", consumes = "application/json;charset=UTF-8")
    public ApiResponse getMenus(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
        	String orgId=params.getString("orgId");
        	String[] ids=orgId.split(",");
	        paramMap.put("ids", ids);
            List<String> list = orgManageService.getMenus(paramMap);
            List<MenuBean> menuList=new ArrayList<MenuBean>();
            for(String o : list) {
            	 MenuBean menu=new MenuBean();
            	 menu.setMenuId(o);
            	 menuList.add(menu);
            }
            
	        return ApiResponse.ok(menuList);
        } catch (CommonException e) {
	        ApiResponse.of(e);
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:zhangyanling Create At:2012-06-04 Description: [系统管理-机构管理，分配菜单]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "distributeMenus", consumes = "application/json;charset=UTF-8")
    public ApiResponse distributeMenus(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    paramMap.put("param_menuIds", params.getString("param_menuIds"));
        try {
//	        List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
//	        String ids[] = idList.toArray(new String[idList.size()]);
        	String orgId=params.getString("orgId");
        	String ids[]=orgId.split(",");
	        paramMap.put("ids", ids);
            orgManageService.distributeMenus(paramMap);
        } catch (CommonException e) {
	        ApiResponse.of(e);
        }
	    return ApiResponse.ok(ResultEnum.OK);
    }
    
    /**
     * Author:chuhailan Create At:2017-09-01 Description: [系统管理-机构管理，获取菜单分组树]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "getMenuList", consumes = "application/json;charset=UTF-8")
    public ApiResponse getMenuList(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> resMap = new HashMap<>();
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    paramMap.put("param_menuName", params.getString("param_menuName"));
	    paramMap.put("param_menuPath", params.getString("param_menuPath"));
	    try {
		    List<MenuBean> menuList = menuService.getMenuList(paramMap);
		    List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
		    String[] orgId = idList.toArray(new String[idList.size()]);
		    if (orgId.length > 1) {
			    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		    }
		    paramMap.put("ids", orgId);
		    List<String> baseBeanList = this.orgManageService.getMenus(paramMap);
		    JSONArray dataArry = new JSONArray();
		    if (null != menuList && menuList.size() > 0) {
		        for (MenuBean menu : menuList) {
		            JSONObject obj = new JSONObject();
		            obj.put("id", menu.getMenuId());
		            obj.put("pId", menu.getParentMenu());
		            obj.put("name", menu.getMenuName());
		            obj.put("leafLev", "3");// 默认放置三级类型信息
		            dataArry.add(obj);
		        }
		    }
		    String selTypeIds = "";
		    if (null != baseBeanList && baseBeanList.size() > 0) {
		        for (String base : baseBeanList) {
		            if (!"01".equals(base)) {
		                selTypeIds = selTypeIds + "," + base;
		            }
		        }
		    }
		    selTypeIds = null == selTypeIds || selTypeIds.trim().length() == 0 ? "0" : selTypeIds;
		    resMap.put("selTypeIds", selTypeIds.replaceAll(",(.*)", "$1"));
		    resMap.put("menuTree", dataArry);
		    resMap.put("orgIds", orgId[0]);
		    return ApiResponse.ok(resMap);
	    } catch(CommonException e) {
		    e.printStackTrace();
		    return ApiResponse.of(e);
	    }
    }

    /**
     * Author:chuhailan Create At:2017-09-01 Description:
     * [系统管理-机构管理，给组织机构分配菜单权限]
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "authMenuToOrg", consumes = "application/json;charset=UTF-8")
    public ApiResponse authMenuToOrg(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    String orgId = params.getString("orgId");
	    List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
	    String ids[] = idList.toArray(new String[idList.size()]);
	    List<String> menuIds=new ArrayList<String>();
	    if(ids != null && ids.length>0) {
	    	for(int i=0;i<ids.length;i++) {
		    	String menuStr=ids[i];
		    	JSONObject json=JSONObject.parseObject(menuStr);
		    	menuIds.add(json.getString("menuId"));
		    }
	    }
	    ids= menuIds.toArray(new String[menuIds.size()]);
	    try {
            orgManageService.distributeOrgMenu(orgId,ids);
		    return ApiResponse.ok(ResultEnum.OK);
	    } catch (CommonException e) {
		    return ApiResponse.of(e);
	    }
    }

}
